<template>
  <div class="admin-orders">
    <div class="page-header">
      <h1>订单管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="refreshOrders">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="success" @click="exportOrders">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="订单状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="使用中" value="using" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="台球桌">
          <el-select
            v-model="filterForm.tableId"
            placeholder="请选择台球桌"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option v-for="table in tables" :key="table.id"
                      :label="table.table_number" :value="table.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleFilterChange"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchOrders">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 当前筛选条件显示 -->
      <div v-if="hasActiveFilters" class="active-filters">
        <span class="filter-label">当前筛选条件：</span>
        <el-tag
          v-if="filterForm.status"
          closable
          @close="clearFilter('status')"
          class="filter-tag"
        >
          状态：{{ getStatusText(filterForm.status) }}
        </el-tag>
        <el-tag
          v-if="filterForm.tableId"
          closable
          @close="clearFilter('tableId')"
          class="filter-tag"
        >
          台球桌：{{ getTableName(filterForm.tableId) }}
        </el-tag>
        <el-tag
          v-if="filterForm.dateRange && filterForm.dateRange.length === 2"
          closable
          @close="clearFilter('dateRange')"
          class="filter-tag"
        >
          日期：{{ filterForm.dateRange[0] }} 至 {{ filterForm.dateRange[1] }}
        </el-tag>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="orders"
        v-loading="loading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="order_number" label="订单号" width="180" />
        <el-table-column prop="user_name" label="用户" width="120" />
        <el-table-column prop="table_name" label="台球桌" width="100" />
        <el-table-column label="开始时间" width="150">
          <template #default="scope">
            <span>{{ formatTimeDisplay(scope.row.booking_date, scope.row.start_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="150">
          <template #default="scope">
            <span>{{ formatTimeDisplay(scope.row.booking_date, scope.row.end_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长(小时)" width="100" />
        <el-table-column prop="total_amount" label="金额" width="100">
          <template #default="scope">
            <span class="amount">￥{{ scope.row.total_amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="150" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <div class="order-action-buttons">
              <el-button
                v-if="scope.row.status === 'pending'"
                type="success"
                size="small"
                @click="confirmPayment(scope.row)"
              >
                确认支付
              </el-button>
              <el-button
                v-if="scope.row.status === 'confirmed'"
                type="primary"
                size="small"
                @click="startUsing(scope.row)"
              >
                开始使用
              </el-button>
              <el-button
                v-if="scope.row.status === 'using'"
                type="warning"
                size="small"
                @click="completeOrder(scope.row)"
              >
                结束使用
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewOrderDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button
                v-if="['pending', 'confirmed'].includes(scope.row.status)"
                type="danger"
                size="small"
                @click="cancelOrder(scope.row)"
              >
                取消
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="order-detail-content">
        <div class="detail-section">
          <h4 class="section-title">📋 基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">订单号:</span>
              <span class="value">{{ selectedOrderDetail.order_number }}</span>
            </div>
            <div class="detail-item">
              <span class="label">用户:</span>
              <span class="value">{{ selectedOrderDetail.user_name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">台球桌:</span>
              <span class="value">{{ selectedOrderDetail.table_name }} ({{ selectedOrderDetail.tableType || '未知类型' }})</span>
            </div>
            <div class="detail-item">
              <span class="label">状态:</span>
              <el-tag :type="getStatusType(selectedOrderDetail.status)">
                {{ getStatusText(selectedOrderDetail.status) }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4 class="section-title">⏰ 时间信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">开始时间:</span>
              <span class="value">{{ selectedOrderDetail.start_time }}</span>
            </div>
            <div class="detail-item">
              <span class="label">结束时间:</span>
              <span class="value">{{ selectedOrderDetail.end_time }}</span>
            </div>
            <div class="detail-item">
              <span class="label">时长:</span>
              <span class="value">{{ selectedOrderDetail.duration }}小时</span>
            </div>
            <div class="detail-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ selectedOrderDetail.create_time }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4 class="section-title">💰 费用信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">总金额:</span>
              <span class="value amount">￥{{ selectedOrderDetail.total_amount }}</span>
            </div>
            <div class="detail-item">
              <span class="label">联系电话:</span>
              <span class="value">{{ selectedOrderDetail.phone || '未提供' }}</span>
            </div>
          </div>
        </div>

        <div v-if="selectedOrderDetail.remark" class="detail-section">
          <h4 class="section-title">📝 备注信息</h4>
          <div class="remark-content">
            {{ selectedOrderDetail.remark }}
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDetailVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAllOrders, updateOrderStatus as updateOrderStatusAPI } from '../../api/order';
import { getTables } from '../../api/table';
import { Refresh, Download } from '@element-plus/icons-vue';
import { formatRelativeTime } from '../../utils/dateFormat';

export default {
  name: 'AdminOrders',

  components: {
    Refresh,
    Download
  },

  setup() {
    const loading = ref(false);
    const orders = ref([]);
    const tables = ref([]);

    // 筛选表单
    const filterForm = reactive({
      status: '',
      tableId: '',
      dateRange: []
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0
    });

    // 模拟订单数据
    const mockOrders = [
      {
        id: 1,
        order_number: 'ORD202309250001',
        user_name: '张三',
        table_name: '1号台',
        start_time: '2023-09-25 14:00:00',
        end_time: '2023-09-25 16:00:00',
        duration: 2,
        total_amount: 40,
        status: 'completed',
        create_time: '2023-09-25 13:45:00'
      },
      {
        id: 2,
        order_number: 'ORD202309250002',
        user_name: '李四',
        table_name: '3号台',
        start_time: '2023-09-25 16:00:00',
        end_time: '2023-09-25 18:00:00',
        duration: 2,
        total_amount: 60,
        status: 'using',
        create_time: '2023-09-25 15:30:00'
      },
      {
        id: 3,
        order_number: 'ORD202309250003',
        user_name: '王五',
        table_name: '5号台',
        start_time: '2023-09-25 19:00:00',
        end_time: '2023-09-25 21:00:00',
        duration: 2,
        total_amount: 80,
        status: 'confirmed',
        create_time: '2023-09-25 18:45:00'
      },
      {
        id: 4,
        order_number: 'ORD202309250004',
        user_name: '赵六',
        table_name: '2号台',
        start_time: '2023-09-25 20:00:00',
        end_time: '2023-09-25 22:00:00',
        duration: 2,
        total_amount: 40,
        status: 'pending',
        create_time: '2023-09-25 19:30:00'
      }
    ];

    // 模拟台球桌数据
    const mockTables = [
      { id: 1, table_number: '1号台' },
      { id: 2, table_number: '2号台' },
      { id: 3, table_number: '3号台' },
      { id: 4, table_number: '4号台' },
      { id: 5, table_number: '5号台' }
    ];

    // 获取订单状态类型
    const getStatusType = (status) => {
      const statusMap = {
        pending: 'warning',
        confirmed: 'info',
        using: 'primary',
        completed: 'success',
        cancelled: 'danger'
      };
      return statusMap[status] || 'info';
    };

    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待支付',
        confirmed: '已支付',
        using: '使用中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[status] || '未知';
    };

    // 格式化时间显示为标准格式 "2025-01-01 12:12:12"
    const formatTimeDisplay = (date, time) => {
      if (!date || !time) return '';

      try {
        // 处理日期部分
        let dateStr = '';
        if (date instanceof Date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          dateStr = `${year}-${month}-${day}`;
        } else if (typeof date === 'string') {
          // 如果是字符串，尝试解析
          const dateObj = new Date(date);
          if (!isNaN(dateObj.getTime())) {
            const year = dateObj.getFullYear();
            const month = String(dateObj.getMonth() + 1).padStart(2, '0');
            const day = String(dateObj.getDate()).padStart(2, '0');
            dateStr = `${year}-${month}-${day}`;
          } else {
            // 如果解析失败，直接使用字符串的前10位（假设是YYYY-MM-DD格式）
            dateStr = date.substring(0, 10);
          }
        }

        // 处理时间部分，确保格式为 HH:MM:SS
        let timeStr = '';
        if (typeof time === 'string') {
          // 如果时间格式是 HH:MM，添加秒数
          if (time.length === 5 && time.includes(':')) {
            timeStr = `${time}:00`;
          } else if (time.length === 8 && time.split(':').length === 3) {
            timeStr = time;
          } else {
            timeStr = time;
          }
        }

        return `${dateStr} ${timeStr}`;
      } catch (error) {
        console.error('时间格式化错误:', error);
        return `${date} ${time}`;
      }
    };

    // 获取订单列表
    const fetchOrders = async () => {
      try {
        loading.value = true;

        const params = {
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
          status: filterForm.status,
        };

        if (filterForm.dateRange && filterForm.dateRange.length === 2) {
          params.date_from = filterForm.dateRange[0].toISOString().split('T')[0];
          params.date_to = filterForm.dateRange[1].toISOString().split('T')[0];
        }

        const response = await getAllOrders(params);

        if (response.success) {
          const ordersList = response.data.items || response.data.orders || [];
          orders.value = ordersList.map(order => ({
            id: order.id,
            order_number: order.order_number || `ORD${String(order.id).padStart(6, '0')}`,
            user_name: order.real_name || order.username || '未知用户',
            table_name: order.table_name || order.table_number,
            booking_date: order.booking_date,
            start_time: order.start_time,
            end_time: order.end_time,
            duration: order.duration,
            total_amount: parseFloat(order.total_cost || 0),
            status: order.status,
            create_time: formatRelativeTime(order.created_at),
            phone: order.phone,
            remark: order.remark || '',
            tableType: order.table_type
          }));
          pagination.total = response.data.total || ordersList.length;
        } else {
          ElMessage.error('获取订单列表失败');
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        ElMessage.error('获取订单列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取台球桌列表
    const fetchTables = async () => {
      try {
        const response = await getTables();
        if (response.success) {
          // 处理后端返回的数据格式：{success: true, data: {items: [...], total: 8}}
          tables.value = response.data.items || response.data.tables || response.data;
        } else {
          ElMessage.error('获取台球桌列表失败');
        }
      } catch (error) {
        console.error('获取台球桌列表失败:', error);
        ElMessage.error('获取台球桌列表失败');
      }
    };

    // 搜索订单
    const searchOrders = () => {
      fetchOrders();
    };

    // 是否有激活的筛选条件
    const hasActiveFilters = computed(() => {
      return filterForm.status ||
             filterForm.tableId ||
             (filterForm.dateRange && filterForm.dateRange.length === 2);
    });

    // 筛选条件变化处理
    const handleFilterChange = () => {
      fetchOrders();
    };

    // 清除单个筛选条件
    const clearFilter = (filterKey) => {
      if (filterKey === 'dateRange') {
        filterForm.dateRange = [];
      } else {
        filterForm[filterKey] = '';
      }
      fetchOrders();
    };

    // 获取台球桌名称
    const getTableName = (tableId) => {
      const table = tables.value.find(t => t.id === tableId);
      return table ? table.table_number : '未知';
    };

    // 重置筛选条件
    const resetFilter = () => {
      filterForm.status = '';
      filterForm.tableId = '';
      filterForm.dateRange = [];
      fetchOrders();
    };

    // 刷新订单
    const refreshOrders = () => {
      fetchOrders();
      ElMessage.success('刷新成功');
    };

    // 导出订单
    const exportOrders = () => {
      ElMessage.success('导出功能开发中...');
    };

    // 更新订单状态
    const updateOrderStatus = async (orderId, newStatus) => {
      try {
        const response = await updateOrderStatusAPI(orderId, { status: newStatus });
        if (response.success) {
          ElMessage.success('订单状态更新成功');
          fetchOrders(); // 重新加载订单列表
        } else {
          ElMessage.error('订单状态更新失败');
        }
      } catch (error) {
        console.error('订单状态更新失败:', error);
        ElMessage.error('订单状态更新失败');
      }
    };

    // 确认支付
    const confirmPayment = (order) => {
      ElMessageBox.confirm(
        `确认订单 ${order.order_number} 已支付？`,
        '确认支付',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        // 更新订单状态
        await updateOrderStatus(order.id, 'confirmed');
      }).catch(() => {
        ElMessage.info('已取消操作');
      });
    };

    // 开始使用
    const startUsing = (order) => {
      ElMessageBox.confirm(
        `确认开始使用台球桌 ${order.table_name}？`,
        '开始使用',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(async () => {
        await updateOrderStatus(order.id, 'using');
      }).catch(() => {
        ElMessage.info('已取消操作');
      });
    };

    // 完成订单
    const completeOrder = (order) => {
      ElMessageBox.confirm(
        `确认结束使用台球桌 ${order.table_name}？`,
        '结束使用',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        await updateOrderStatus(order.id, 'completed');
      }).catch(() => {
        ElMessage.info('已取消操作');
      });
    };

    // 取消订单
    const cancelOrder = (order) => {
      ElMessageBox.confirm(
        `确认取消订单 ${order.order_number}？`,
        '取消订单',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error'
        }
      ).then(async () => {
        await updateOrderStatus(order.id, 'cancelled');
      }).catch(() => {
        ElMessage.info('已取消操作');
      });
    };

    // 订单详情对话框
    const orderDetailVisible = ref(false);
    const selectedOrderDetail = ref({});

    // 查看订单详情
    const viewOrderDetail = (order) => {
      selectedOrderDetail.value = order;
      orderDetailVisible.value = true;
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchOrders();
    };

    const handleCurrentChange = (page) => {
      pagination.currentPage = page;
      fetchOrders();
    };

    const selectedOrders = ref([]);
    const handleSelectionChange = (val) => {
      selectedOrders.value = val;
    };

    // 初始化
    onMounted(() => {
      fetchOrders();
      fetchTables();
    });

    return {
      loading,
      orders,
      tables,
      filterForm,
      pagination,
      hasActiveFilters,
      getStatusType,
      getStatusText,
      formatTimeDisplay,
      getTableName,
      handleFilterChange,
      clearFilter,
      searchOrders,
      resetFilter,
      refreshOrders,
      exportOrders,
      confirmPayment,
      startUsing,
      completeOrder,
      cancelOrder,
      viewOrderDetail,
      orderDetailVisible,
      selectedOrderDetail,
      handleSizeChange,
      handleCurrentChange,
      selectedOrders,
      handleSelectionChange
    };
  }
};
</script>

<style scoped>
.admin-orders {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

/* 当前筛选条件显示 */
.active-filters {
  margin-top: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
  font-weight: 500;
}

.filter-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.table-card {
  margin-bottom: 20px;
}

.amount {
  font-weight: bold;
  color: #e6a23c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 订单操作按钮容器 */
.order-action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 280px;
  overflow-x: auto;
  padding: 2px 0;
}

.order-action-buttons::-webkit-scrollbar {
  height: 4px;
}

.order-action-buttons::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.order-action-buttons::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.order-action-buttons::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.order-action-buttons .el-button {
  flex-shrink: 0;
  margin: 0;
}

/* 订单详情对话框样式 */
.order-detail-content {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.detail-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 12px;
}

.detail-item .value {
  color: #303133;
  flex: 1;
}

.detail-item .value.amount {
  font-size: 18px;
  font-weight: bold;
  color: #e6a23c;
}

.remark-content {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  color: #606266;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-orders {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }
}

.el-table .el-table__header .el-checkbox {
  margin-right: 0;
}
</style>
